package com.example.cupid.controller;

import com.example.cupid.pojo.Order;
import com.example.cupid.pojo.User;
import com.example.cupid.pojo.Wechat;
import com.example.cupid.service.*;
import com.example.cupid.util.MsgUtil;
import com.example.cupid.util.Verification;
import com.google.gson.internal.$Gson$Preconditions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.net.URLDecoder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 2021/9/6
 * 支付Controller
 **/
@RestController
@RequestMapping("/pay")
public class PayController {
    @Autowired
    private AdminService adminService;

    //注入接口 不要注入实现类 人傻了
    @Autowired
    private PayService payService;
    @Autowired
    private OrderService orderService;
    @Autowired
    private WechatService wechatService;
    @Autowired
    private TagService tagService;

    /**
     * 下单支付
     */
    @PostMapping(value = "/saveConfirm",produces = {"text/html;charset=UTF-8"})
    public Object pay(Wechat wechat, @RequestParam List<Integer> tags, HttpServletRequest request)throws Exception{
        System.out.println(wechat);
        System.out.println(tags);
        HttpSession session = request.getSession();
        User loginUser =(User) session.getAttribute("loginUser");
        String msg = loginUser.getId()+wechat.toString()+tags.toString();
        return payService.savePay(msg);
    }

    @PostMapping("/saveNotify")
    public void notifyAsyn(HttpServletRequest request) throws ParseException, UnsupportedEncodingException {
        Map<String, String[]> map = request.getParameterMap();
        String status = map.get("trade_status")[0];
        String trade_no = map.get("trade_no")[0];
        int count = orderService.checkOrderByNo(trade_no);
        if(status.equals("TRADE_SUCCESS")&&count==0){
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date gmt_create = sdf.parse(map.get("gmt_create")[0]);
            Date gmt_payment = sdf.parse(map.get("gmt_payment")[0]);
            Double total_amount = new Double(map.get("total_amount")[0]);
            String out_trade_no = map.get("out_trade_no")[0];
//            将投放的微信保存到数据库
            String passback_params = URLDecoder.decode(request.getParameter("passback_params"), "UTF-8");
//            System.out.println("passback_params="+passback_params);
            Integer userId = Integer.parseInt(passback_params.substring(0,passback_params.indexOf("W")));
            Order order = new Order(total_amount,gmt_create,gmt_payment,out_trade_no,trade_no,userId);
            // 将订单保存到数据库
            orderService.saveOrder(order);
            Wechat wechat = MsgUtil.msgToWechat(passback_params);
            String[] tagIds = MsgUtil.msgToTags(passback_params);
//            将微信保存到数据库
            wechatService.saveWechat(wechat);
            System.out.println("保存微信==========="+wechat);
            int wechatId = wechatService.getWechat(wechat.getWechat()).getId();
//            修改用户存放的微信中间表
            wechatService.saveUserWechatSave(userId,wechatId);
            User user = adminService.checkUserById(userId);
            Double totalPay = user.getTotalPay();
            adminService.updatePay(total_amount+totalPay,userId);
            for (String tagId : tagIds) {
            //修改微信和标签中间表
                tagService.saveWechatTag(wechatId,tagId);
            }
        }else{
            System.out.println("trade_status = "+status);
        }
    }

    @PostMapping(value = "/randomTakeConfirm",produces = {"text/html;charset=UTF-8"})
    public Object randomTakePay(int sex,HttpServletRequest request)throws Exception{
        HttpSession session = request.getSession();
        User loginUser =(User) session.getAttribute("loginUser");
        String msg =loginUser.getId()+"sex="+sex;
        return payService.randomTakePay(msg);
    }

    @PostMapping("/randomTakeNotify")
    public void randomTakeNotifyAsyn(HttpServletRequest request) throws ParseException, UnsupportedEncodingException {
        Map<String, String[]> map = request.getParameterMap();
        String status = map.get("trade_status")[0];
        String trade_no = map.get("trade_no")[0];
        int count = orderService.checkOrderByNo(trade_no);
        if(status.equals("TRADE_SUCCESS")&&count==0){
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date gmt_create = sdf.parse(map.get("gmt_create")[0]);
            Date gmt_payment = sdf.parse(map.get("gmt_payment")[0]);
            Double total_amount = new Double(map.get("total_amount")[0]);
            String out_trade_no = map.get("out_trade_no")[0];
            //随即获取一个微信
            String passback_params = URLDecoder.decode(request.getParameter("passback_params"), "UTF-8");
            System.out.println("passback_params="+passback_params);
            int userId = Integer.parseInt(passback_params.substring(0, passback_params.indexOf('s')));
            Order order = new Order(total_amount,gmt_create,gmt_payment,out_trade_no,trade_no,userId);
//          将订单保存到数据库
            User user = adminService.checkUserById(userId);
            Double totalPay = user.getTotalPay();
            adminService.updatePay(total_amount+totalPay,userId);
            orderService.saveOrder(order);

        }else{
            System.out.println("trade_status = "+status);
        }
    }

    @PostMapping(value = "/signalTakeConfirm", produces = {"text/html;charset=UTF-8"})
    public Object signalTakePay(Wechat wechat, HttpServletRequest request) throws Exception {
        System.out.println("wechat = "+wechat);
        HttpSession session = request.getSession();
        User loginUser = (User)session.getAttribute("loginUser");
        int userId = loginUser.getId();
        String msg = userId+wechat.toString();
        return payService.signalTakePay(msg);
    }

    @PostMapping("/signalTakeNotify")
    public void signalTakeNotifyAsyn(HttpServletRequest request) throws Exception {
        Map<String, String[]> map = request.getParameterMap();
        String status = map.get("trade_status")[0];
        String trade_no = map.get("trade_no")[0];
        int count = orderService.checkOrderByNo(trade_no);
        if(status.equals("TRADE_SUCCESS")&&count==0){
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date gmt_create = sdf.parse(map.get("gmt_create")[0]);
            Date gmt_payment = sdf.parse(map.get("gmt_payment")[0]);
            Double total_amount = new Double(map.get("total_amount")[0]);
            String out_trade_no = map.get("out_trade_no")[0];
//          passback_params => 20Wechat(id=0, wechat=null, sex=1, school=湖南工业大学, grade=博士生, description=null, tagNames=null)[3, 4, 6]
            String passback_params = URLDecoder.decode(request.getParameter("passback_params"), "UTF-8");
            System.out.println("signalTakeNotifyAsyn->passback_params = "+passback_params);
            Integer userId = Integer.parseInt(passback_params.substring(0,passback_params.indexOf("W")));
            Order order = new Order(total_amount,gmt_create,gmt_payment,out_trade_no,trade_no,userId);
//          将订单保存到数据库
            orderService.saveOrder(order);
            User user = adminService.checkUserById(userId);
            Double totalPay = user.getTotalPay();
            adminService.updatePay(total_amount+totalPay,userId);
        }else{
            System.out.println("trade_status = "+status);
        }

    }
}
